﻿#region License
/*  YanYeovil
    Copyright (c) 2014, Alexey A. Popov
    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, are
    permitted provided that the following conditions are met:

    - Redistributions of source code must retain the above copyright notice, this list
      of conditions and the following disclaimer.

    - Redistributions in binary form must reproduce the above copyright notice, this list
      of conditions and the following disclaimer in the documentation and/or other materials
      provided with the distribution.

    - Neither the propertyName of the Alexey A. Popov nor the names of its contributors may be used to
      endorse or promote products derived from this software without specific prior written
      permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS *AS IS* AND ANY EXPRESS
    OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
    AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
    DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
    IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
    OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

using System;
using System.Data;
using System.Globalization;
using System.Reflection;

namespace Pvax.Data
{
    /// <summary>
    /// Maps a propery to a DB column.
    /// </summary>
    class PropertyMapping
    {
        Func<object, object> getter;

        Action<object, object> setter;

        /// <summary>
        /// Creates and initializes a new instance of the <see cref="PropertyMapping"/>.
        /// </summary>
        /// <param name="propInfo">The property descriptor.</param>
        internal PropertyMapping(PropertyInfo propInfo)
        {
            if(null == propInfo)
                throw new ArgumentNullException("propInfo", Properties.Resources.ErrNullParam);

            this.type = propInfo.PropertyType;
            this.name = propInfo.Name;
            //// Determine the actual types of the getter/setter pair and their closure
            Type closureType = typeof(Closure<,>).MakeGenericType(propInfo.DeclaringType, propInfo.PropertyType);
            Type getterType = typeof(Func<,>).MakeGenericType(propInfo.DeclaringType, propInfo.PropertyType);
            Type setterType = typeof(Action<,>).MakeGenericType(propInfo.DeclaringType, propInfo.PropertyType);
            //// Instantiate the strongly typed closure
            //// It is OK to use reflection here, one Invoke() per class per property
            //// I use a little bit faster versions of the reflection methods here
            //// NB: If Closure<T1,T2> ctor changes visibility, change the BindingFlags in the next line
            ConstructorInfo thunkCtor = closureType.GetConstructor(BindingFlags.ExactBinding | BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(Delegate), typeof(Delegate) }, null);
            Closure closure = (Closure)thunkCtor.Invoke(BindingFlags.ExactBinding, null, new Delegate[] { Delegate.CreateDelegate(getterType, propInfo.GetGetMethod()), Delegate.CreateDelegate(setterType, propInfo.GetSetMethod()) }, CultureInfo.InvariantCulture);
            this.getter = closure.Get;
            this.setter = closure.Set;
        }

        string name;

        /// <summary>
        /// Gets the name of the property.
        /// </summary>
        internal string Name
        {
            get
            {
                return name;
            }
        }

        Type type;

        /// <summary>
        /// Gets the type of the database field.
        /// </summary>
        internal DbType DbType
        {
            get
            {
                if(type == typeof(bool) || type == typeof(bool?))
                    return DbType.Boolean;
                if(type == typeof(byte) || type == typeof(byte?))
                    return DbType.Byte;
                if(type == typeof(byte[]))
                    return DbType.Binary;
                if(type == typeof(short) || type == typeof(short?))
                    return DbType.Int16;
                if(type == typeof(int) || type == typeof(int?))
                    return DbType.Int32;
                if(type == typeof(long) || type == typeof(long?))
                    return DbType.Int64;
                if(type == typeof(sbyte) || type == typeof(sbyte?))
                    return DbType.SByte;
                if(type == typeof(ushort) || type == typeof(ushort?))
                    return DbType.UInt16;
                if(type == typeof(uint) || type == typeof(uint?))
                    return DbType.UInt32;
                if(type == typeof(ulong) || type == typeof(ulong?))
                    return DbType.UInt64;
                if(type == typeof(string))
                    return DbType.String;
                if(type == typeof(float) || type == typeof(float?))
                    return DbType.Single;
                if(type == typeof(double) || type == typeof(double?))
                    return DbType.Double;
                if(type == typeof(decimal) || type == typeof(decimal?))
                    return DbType.Decimal;
                if(type == typeof(DateTime) || type == typeof(DateTime?))
                    return DbType.DateTime;
                if(type == typeof(DateTimeOffset) || type == typeof(DateTimeOffset?))
                    return DbType.DateTimeOffset;
                throw new InvalidCastException();
            }
        }

        /// <summary>
        /// Returns the string representation of the <see cref="PropertyMapping"/> instance.
        /// </summary>
        /// <returns>The display string that represents the object.</returns>
        public override string ToString()
        {
            return String.Join(String.Empty, "[", name, ",", "]");
        }

        /// <summary>
        /// Pulls the value of the property from the database field.
        /// </summary>
        /// <param name="instance">The object to set the property for.</param>
        /// <param name="reader">The instance of the <see cref="IDataReader"/> to pull the data from.</param>
        internal void Pull(object instance, IDataReader reader)
        {
            setter(instance, reader[Name]);
        }

        /// <summary>
        /// Pushes the value of the property to the database.
        /// </summary>
        /// <param name="instance">The object to get the property from.</param>
        /// <param name="parameter">The instance of the <see cref="IDataParameter"/> to push the data to.</param>
        internal void Push(object instance, IDataParameter parameter)
        {
            parameter.Value = getter(instance);
        }
    }
}
